#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语音控制快速启动脚本

提供简单的命令行界面来启动和测试语音控制功能
"""

import sys
import os
import time
import argparse

# 添加当前目录到路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def check_dependencies():
    """检查依赖是否安装"""
    missing_deps = []
    
    try:
        import pyaudio
    except ImportError:
        missing_deps.append("pyaudio")
    
    try:
        import numpy
    except ImportError:
        missing_deps.append("numpy")
    
    try:
        import requests
    except ImportError:
        missing_deps.append("requests")
    
    try:
        import flask
    except ImportError:
        missing_deps.append("flask")
    
    if missing_deps:
        print("❌ 缺少以下依赖包:")
        for dep in missing_deps:
            print(f"   - {dep}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        print("\n或者单独安装:")
        for dep in missing_deps:
            print(f"pip install {dep}")
        return False
    
    return True


def test_audio_devices():
    """测试音频设备"""
    try:
        from services.realtime_audio_capture import RealTimeAudioCapture
        
        print("🎧 检测音频设备...")
        capture = RealTimeAudioCapture()
        capture.list_audio_devices()
        
        return True
    except Exception as e:
        print(f"❌ 音频设备检测失败: {e}")
        return False


def run_voice_control():
    """运行语音控制"""
    try:
        from services.voice_control_service import VoiceControlService
        
        print("🚀 启动语音控制服务...")
        
        # 创建语音控制服务
        voice_service = VoiceControlService()
        
        # 设置简单的回调
        def on_command_result(text: str, result: dict):
            if result.get("success"):
                print(f"✅ 指令执行成功: {text}")
            else:
                print(f"❌ 指令执行失败: {text}")
        
        voice_service.on_command_result = on_command_result
        
        # 启动语音控制
        success = voice_service.start_voice_control()
        
        if success:
            print("\n🎤 语音控制已启动!")
            print("💡 现在可以开始说话了，支持的指令:")
            print("   - '播放音乐'")
            print("   - '写一篇文章'") 
            print("   - '打开记事本'")
            print("   - '创建文件'")
            print("\n按 Ctrl+C 退出")
            
            try:
                while voice_service.is_active:
                    time.sleep(0.1)
            except KeyboardInterrupt:
                print("\n👋 用户退出语音控制")
        else:
            print("❌ 语音控制启动失败")
            
    except Exception as e:
        print(f"❌ 运行语音控制失败: {e}")
        import traceback
        traceback.print_exc()


def run_text_test():
    """运行文本指令测试"""
    try:
        from services.voice_control_service import VoiceControlService
        
        print("📝 文本指令测试模式")
        
        voice_service = VoiceControlService()
        
        test_commands = [
            "你好，请帮我播放音乐",
            "帮我写一篇小说",
            "打开文本编辑器",
            "创建一个文件叫test.txt"
        ]
        
        print(f"🧪 将测试 {len(test_commands)} 个指令:")
        for i, cmd in enumerate(test_commands, 1):
            print(f"  {i}. {cmd}")
        
        input("\n按回车开始测试...")
        
        for i, command in enumerate(test_commands, 1):
            print(f"\n--- 测试 {i}/{len(test_commands)}: {command} ---")
            
            try:
                result = voice_service.process_text_command(command)
                
                # 显示简要结果
                if result.get("success"):
                    print(f"✅ 成功: {result.get('message', '')}")
                else:
                    print(f"❌ 失败: {result.get('message', '')}")
                
            except Exception as e:
                print(f"❌ 处理失败: {e}")
            
            # 等待一下再处理下一个
            if i < len(test_commands):
                time.sleep(2)
        
        print(f"\n📊 文本指令测试完成!")
        
    except Exception as e:
        print(f"❌ 文本测试失败: {e}")


def run_audio_test():
    """运行音频录制测试"""
    try:
        from services.realtime_audio_capture import RealTimeAudioCapture
        
        print("🎤 音频录制测试")
        
        capture = RealTimeAudioCapture()
        
        # 显示设备
        capture.list_audio_devices()
        
        # 选择设备
        device_index = None
        try:
            device_input = input("\n请输入设备编号 (回车使用默认): ").strip()
            if device_input:
                device_index = int(device_input)
        except ValueError:
            print("⚠️ 无效设备编号，使用默认设备")
        
        print("\n选择测试类型:")
        print("1. 固定时长录音测试")
        print("2. VAD语音检测测试")
        
        try:
            choice = input("请选择 (1-2): ").strip()
            
            if choice == "1":
                # 固定时长录音
                duration = float(input("录音时长(秒，默认3): ") or "3")
                print(f"\n🎤 开始录制 {duration} 秒...")
                print("请开始说话...")
                
                audio_file = capture.record_fixed_duration(duration, device_index)
                if audio_file:
                    print(f"✅ 录制成功: {audio_file}")
                    
                    # 获取文件大小
                    file_size = os.path.getsize(audio_file)
                    print(f"📁 文件大小: {file_size} 字节")
                else:
                    print("❌ 录制失败")
            
            elif choice == "2":
                # VAD测试
                print("\n🎤 VAD语音检测测试")
                print("💡 开始说话，系统会自动检测语音开始和结束")
                print("   按 Ctrl+C 退出")
                
                def on_speech_start(vad_result):
                    print(f"🟢 检测到语音开始! (音量: {vad_result['volume']:.4f})")
                
                def on_speech_end(vad_result, audio_file):
                    duration = vad_result.get('speech_duration', 0)
                    print(f"🔴 语音结束! (时长: {duration:.2f}秒, 文件: {audio_file})")
                
                capture.on_speech_start = on_speech_start
                capture.on_speech_end = on_speech_end
                
                capture.start_listening(device_index)
                
                try:
                    while True:
                        time.sleep(0.1)
                except KeyboardInterrupt:
                    print("\n👋 VAD测试结束")
                finally:
                    capture.stop_listening()
            
            else:
                print("❌ 无效选择")
        
        except Exception as e:
            print(f"❌ 音频测试失败: {e}")
        finally:
            capture.cleanup_temp_files()
        
    except Exception as e:
        print(f"❌ 音频测试失败: {e}")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='语音控制快速启动脚本')
    parser.add_argument('mode', nargs='?', choices=['voice', 'text', 'audio', 'check', 'tos'], 
                       default='voice', help='运行模式')
    parser.add_argument('--no-check', action='store_true', help='跳过依赖检查')
    
    args = parser.parse_args()
    
    print("🎯 语音控制系统")
    print("=" * 40)
    
    # 检查依赖
    if not args.no_check:
        print("🔍 检查依赖...")
        if not check_dependencies():
            return 1
        print("✅ 依赖检查通过")
    
    # 根据模式运行
    if args.mode == 'check':
        print("\n🧪 系统检查模式")
        
        # 检查依赖
        print("\n1. 依赖检查:")
        deps_ok = check_dependencies()
        print(f"   结果: {'✅ 通过' if deps_ok else '❌ 失败'}")
        
        # 检查音频设备
        print("\n2. 音频设备检查:")
        audio_ok = test_audio_devices()
        print(f"   结果: {'✅ 通过' if audio_ok else '❌ 失败'}")
        
        # 检查服务模块
        print("\n3. 服务模块检查:")
        try:
            from services.voice_control_service import VoiceControlService
            from services.asr_service import MinimalASR
            from services.intelligent_command_service import IntelligentCommandService
            print("   结果: ✅ 通过")
            modules_ok = True
        except Exception as e:
            print(f"   结果: ❌ 失败 - {e}")
            modules_ok = False
        
        # 总结
        print(f"\n📊 系统检查结果:")
        print(f"   依赖: {'✅' if deps_ok else '❌'}")
        print(f"   音频: {'✅' if audio_ok else '❌'}")
        print(f"   模块: {'✅' if modules_ok else '❌'}")
        
        if all([deps_ok, audio_ok, modules_ok]):
            print("\n🎉 系统准备就绪，可以使用语音控制功能!")
            print("\n使用方法:")
            print("  python start_voice_control.py voice    # 启动语音控制")
            print("  python start_voice_control.py text     # 文本指令测试")
            print("  python start_voice_control.py audio    # 音频录制测试")
            print("  python start_voice_control.py tos      # TOS上传测试")
        else:
            print("\n⚠️ 系统存在问题，请解决后再使用")
    
    elif args.mode == 'voice':
        print("\n🎤 语音控制模式")
        run_voice_control()
    
    elif args.mode == 'text':
        print("\n📝 文本指令测试模式")
        run_text_test()
    
    elif args.mode == 'audio':
        print("\n🎤 音频录制测试模式")
        run_audio_test()
    
    elif args.mode == 'tos':
        print("\n📤 TOS上传测试模式")
        # 导入并运行TOS测试
        try:
            import subprocess
            result = subprocess.run([sys.executable, "test_tos_upload.py"], cwd=os.path.dirname(os.path.abspath(__file__)))
            return result.returncode
        except Exception as e:
            print(f"❌ TOS测试失败: {e}")
            return 1
    
    return 0


if __name__ == "__main__":
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n👋 用户退出")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 程序异常: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
